#!C:\Python27\python

errorfile = file("errorlog.txt", "a")

import sys
import os, glob
import msvcrt
from ReqHandler import handler
from Output import output
import StateManager
from Cookie import SimpleCookie

MSG501 = "Status: 501 Not Implemented\r\nContent-Length: 0\r\nContent-Type: text/plain\r\n\r\n"
MSG404 = "Status: 404 Not Found\r\nContent-Length: 0\r\nContent-Type: text/plain\r\n\r\n"
MSG0LEN = "Content-Length: 0\r\nContent-Type: text/plain\r\n\r\n"

def GetHttpCookie():
        try:
            return SimpleCookie(os.environ["HTTP_COOKIE"])
        except:
            cookie = SimpleCookie()
            cookie["user"] = handler.defaultuser
            
            os.environ["HTTP_COOKIE"] = str(cookie)
            return cookie

def GetContentType(name):
    contentType = ''
    if name.endswith(".m3u8"):
        contentType = "application/vnd.apple.mpegurl"
    elif name.endswith(".ts"):
        contentType = "video/mpeg"
    elif name.endswith(".jpg"):
        contentType = "image/jpeg"
    elif name.endswith(".key"):
        contentType = "application/binary"
    return contentType

def writeFileToStdout(name):
    f = open(name, "rb")
    while True:
        next = f.read(4096)
        if not next:
            break
        sys.stdout.write(next)
    f.close()

def writeStdinToFile(name):
    fileHandle = open(name, "wb")
    while True:
        next = sys.stdin.read(4096)
        if not next:
            break
        fileHandle.write(next)
    fileHandle.close()
    
def GetModTime(name):
    try:
        return os.path.getmtime(name)
    except:
        return 0

msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)



sys.stderr = errorfile
                
baseDir = "."

method = os.environ.get("REQUEST_METHOD")
name = baseDir + os.environ.get("PATH_INFO", "")

existcookie = GetHttpCookie()
user = existcookie["user"].value
if user is None:
    user = handler.defaultuser

contentType = GetContentType(name)

#dispatching the handle
handleRequest = handler(user, output.STDMODE, output.GET_Request)
#handleRequest.output.logthis("User is: " + user, output.GET_Request)
#handleRequest.handle(method, name, contentType)
stateMgr = StateManager.StateMgr(user)

if method == "MKCOL":
    os.mkdir(os.path.dirname(name))
    sys.stdout.write(MSG0LEN)
elif name.endswith(".key"):
    if method == "GET":
        sys.stdout.write("Content-Length: %d\r\nContent-Type: %s\r\n\r\n" % (os.path.getsize(name), contentType))
        writeFileToStdout(name)
    elif method == "PUT":
        writeStdinToFile(name)
        sys.stdout.write("Content-Length: 0\r\nContent-Type: text/plain\r\n\r\n")
elif method == "GET":
    handleRequest.output.logthis("Regular GET for " + name + "{", output.GET_Request)
    
    if name.find("index.m3u8") == -1:   # name anything but index.m3u8
        handleRequest.output.logthis("Invoking StateMgr for " + name, output.GET_Request)
        stateMgr.HandleGET(user, name)  #handler.defaultuser
        handleRequest.output.logthis("StateMgr returned for " + name, output.GET_Request)
        
#        if name.find(".m3u8") != -1:
#            names = glob.glob("%s-*" % name)
#            (latest, filename) = max( (GetModTime(filename),filename) for filename in names)
#            name = filename
#            name = "ad1.m3u8"#stateMgr.adFile
#        elif name.endswith(".ts") and name.find("fileSequence") == -1:
#            name = "fileSequence0.ts"#stateMgr.adFile
#    
#        sys.stdout.write("Content-Length: %d\r\nContent-Type: %s\r\n\r\n" % (os.path.getsize(name), contentType))
#        writeFileToStdout(name)
        handleRequest.output.logthis("Regular GET returned " + name + "}\n", output.GET_Request)
        handleRequest.output.logFile.close()
        #return None
    else:   #index.m3u8 
        sys.stdout.write("Content-Length: %d\r\nContent-Type: %s\r\n\r\n" % (os.path.getsize(name), contentType))
        writeFileToStdout(name)
        handleRequest.output.logthis("}\n", output.GET_Request)
        handleRequest.output.logFile.close()
elif name.find("index.m3u8") == -1 and (name.endswith(".m3u8") or name.endswith("thumb.jpg")):
    handleRequest.output.logthis("Handle .m3u8 for " + method + " " + name + "\r{")
    handleRequest.handle(method, name, contentType)
    handleRequest.output.logthis("}\n")
    handleRequest.output.logFile.close()
elif method == "PUT":
#    handleRequest.output.logthis("Regular PUT for " + name + "{", handler.output.PUT_Request)
    writeStdinToFile(name)
    sys.stdout.write(MSG0LEN)
#    handleRequest.output.logthis("}\n", handler.output.PUT_Request)
#    handleRequest.output.logFile.close()
elif method == "DELETE":
    try:
        os.remove(name)
    except:
        pass
    sys.stdout.write(MSG0LEN)
